package bb.lanxing.fragment.sport;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.Utils;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.R;
import bb.lanxing.activity.sport.SportRecordChartActivity;
import bb.lanxing.adapter.sport.SportRecordCadenceAdapter;
import bb.lanxing.adapter.sport.SportRecordPaceAdapter;
import bb.lanxing.calc.PaceHelper;
import bb.lanxing.databinding.unit.UnitConstants;
import bb.lanxing.fragment.base.BaseFragment;
import bb.lanxing.model.database.ITrackPoint;
import bb.lanxing.model.database.Workout;
import bb.lanxing.model.json.CadenceSection;
import bb.lanxing.model.json.HeartrateSection;
import bb.lanxing.model.json.PowerSection;
import bb.lanxing.model.json.WorkoutExtraInfo;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.view.LinearPercentView;

public class SportRecordChartFragment extends BaseFragment implements View.OnClickListener {
    private final int[] heartRateStrings = {R.string.mine_section_setting_hr_5, R.string.mine_section_setting_hr_4,
            R.string.mine_section_setting_hr_3, R.string.mine_section_setting_hr_2,
            R.string.mine_section_setting_hr_1, R.string.mine_section_setting_0};
    private final int[] heartRateBgs = {R.color.section_item_hr_bg_0_color, R.color.section_item_hr_bg_1_color,
            R.color.section_item_hr_bg_2_color, R.color.section_item_hr_bg_3_color,
            R.color.section_item_hr_bg_4_color, R.color.section_item_hr_bg_5_color};
    private final int[] cadenceStrings = {R.string.mine_section_setting_ca_z1, R.string.mine_section_setting_ca_z2,
            R.string.mine_section_setting_ca_z3, R.string.mine_section_setting_ca_z4};
    private final int[] cadenceBgs = {R.color.sport_record_cadence_bg1, R.color.sport_record_cadence_bg2,
            R.color.sport_record_cadence_bg3, R.color.sport_record_cadence_bg4};
    private final int[] powerStrings = {R.string.power_interval_titles_one, R.string.power_interval_titles_two,
            R.string.power_interval_titles_three, R.string.power_interval_titles_four, R.string.power_interval_titles_five,
            R.string.power_interval_titles_six, R.string.power_interval_titles_seven};
    private final int[] powerBgs = {R.color.history_power_interval_z1, R.color.history_power_interval_z2,
            R.color.history_power_interval_z3, R.color.history_power_interval_z4, R.color.history_power_interval_z5,
            R.color.history_power_interval_z6, R.color.history_power_interval_z7};

    private Workout workout;

    private LinearLayout speedLayout;
    private LineChart speedChart;

    private CardView paceView;
    private LinearLayout paceLayout;
    private RecyclerView paceList;

    private LinearLayout altitudeLayout;
    private LineChart altitudeChart;
    private LinearPercentView slopeView;

    private CardView heartRateView;
    private LinearLayout heartRateLayout;
    private LineChart heartRateChart;
    private RecyclerView heartRateList;

    private CardView cadenceView;
    private LinearLayout cadenceLayout;
    private LineChart cadenceChart;
    private RecyclerView cadenceList;

    private CardView powerView;
    private LinearLayout powerLayout;
    private LineChart powerChart;
    private RecyclerView powerList;

    private final DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private final DecimalFormat decimalFormat2 = new DecimalFormat("0.0");

    private ArrayList<Entry> speedEntries;
    private float maxSpeed;
    private float avgSpeed;
    private ArrayList<Entry> altitudeEntries;
    private float maxAltitude;
    private float avgAltitude;
    private ArrayList<Entry> heartrateEntries;
    private float maxHeartrate;
    private float avgHeartrate;
    private ArrayList<Entry> cadenceEntries;
    private float maxCadence;
    private float avgCadence;
    private ArrayList<Entry> powerEntries;
    private float maxPower;
    private float avgPower;

    public SportRecordChartFragment(Workout workout) {
        this.workout = workout;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_sport_record_chart, container, false);
        speedLayout = view.findViewById(R.id.speedLayout);
        speedLayout.setOnClickListener(this);
        speedChart = view.findViewById(R.id.speedChart);
        speedChart.setOnClickListener(this);
        showSpeedChart();

        paceView = view.findViewById(R.id.paceView);
        paceLayout = view.findViewById(R.id.paceLayout);
        paceList = view.findViewById(R.id.paceList);
        showPaceChart();

        altitudeLayout = view.findViewById(R.id.altitudeLayout);
        altitudeLayout.setOnClickListener(this);
        altitudeChart = view.findViewById(R.id.altitudeChart);
        altitudeChart.setOnClickListener(this);
        slopeView = view.findViewById(R.id.slopeView);
        showAltitudeChart();

        heartRateView = view.findViewById(R.id.heartRateView);
        heartRateLayout = view.findViewById(R.id.heartRateLayout);
        heartRateLayout.setOnClickListener(this);
        heartRateChart = view.findViewById(R.id.heartRateChart);
        heartRateChart.setOnClickListener(this);
        heartRateList = view.findViewById(R.id.heartRateList);
        showHeartRateChart();

        cadenceView = view.findViewById(R.id.cadenceView);
        cadenceLayout = view.findViewById(R.id.cadenceLayout);
        cadenceLayout.setOnClickListener(this);
        cadenceChart = view.findViewById(R.id.cadenceChart);
        cadenceChart.setOnClickListener(this);
        cadenceList = view.findViewById(R.id.cadenceList);
        showCadenceChart();

        powerView = view.findViewById(R.id.powerView);
        powerLayout = view.findViewById(R.id.powerLayout);
        powerLayout.setOnClickListener(this);
        powerChart = view.findViewById(R.id.powerChart);
        powerChart.setOnClickListener(this);
        powerList = view.findViewById(R.id.powerList);
        showPowerChart();
        return view;
    }

    private void showSpeedChart() {
        TextView value = speedLayout.findViewById(R.id.value);
        TextView value1 = speedLayout.findViewById(R.id.value1);
        avgSpeed = (float) workout.getDistance() / workout.getDuration() * 3.6f;
        if ((workout.getSport() == Workout.TYPE_TRAINING)
                || (workout.getSport() == Workout.TYPE_INDOOR_BIKE)
                || (workout.getSport() == Workout.TYPE_BIKE_TRAINER)
                || (workout.getSport() == Workout.TYPE_ROWER)
                || (workout.getSport() == Workout.TYPE_CROSS_TRAINER)) {
            avgSpeed = (float) workout.getAvgSpeed() * 3.6f;
        }
        value.setText(decimalFormat2.format(avgSpeed) + "km/h");
        maxSpeed = (float) workout.getMaxSpeed() * 3.6f;
        value1.setText(decimalFormat.format(maxSpeed) + "km/h");
        List<ITrackPoint> trackpointList = workout.getTrackPointsForChart();
        if (trackpointList == null) {
            return;
        }
        speedEntries = new ArrayList<>();
        for (int i = 0; i < trackpointList.size(); i++) {
            speedEntries.add(new Entry(trackpointList.get(i).getTime() - trackpointList.get(0).getTime(),
                    (float) trackpointList.get(i).getSpeed() * 3.6f));
        }
        initLineChart(speedChart, speedEntries, maxSpeed, avgSpeed, getContext().getColor(R.color.color_21d352), false, 0);
    }

    private void initLineChart(LineChart chart, List<Entry> entries, float maxData, float avgData,
                               int lineColor, boolean filled, int FillColor) {
        LineDataSet dataSet = new LineDataSet(entries, "");
        dataSet.setColor(lineColor);
        dataSet.setLineWidth(1.5f);
        dataSet.setDrawCircles(false);
        dataSet.setAxisDependency(YAxis.AxisDependency.RIGHT);
        dataSet.setDrawFilled(filled);
        if (filled) {
            dataSet.setFillColor(FillColor);
        }
        chart.setData(new LineData(dataSet));
        chart.setDescription(null);
        chart.getLegend().setEnabled(false);
        YAxis axisRight = chart.getAxisRight();
        axisRight.setDrawGridLines(false);
        axisRight.setDrawLabels(false);
        YAxis leftAxis = chart.getAxisLeft();
        leftAxis.setAxisMaximum(maxData * 1.1f);
        leftAxis.setAxisMinimum(0);
        leftAxis.setDrawGridLines(false);
        leftAxis.setLabelCount(5, true);
        LimitLine limitLine = new LimitLine(maxData * 1.1f);
        limitLine.enableDashedLine(10, 10, 0);
        limitLine.setLineColor(Color.GRAY);
        leftAxis.addLimitLine(limitLine);
        LimitLine limitLine1 = new LimitLine(avgData);
        limitLine1.enableDashedLine(10, 10, 0);
        limitLine1.setLineWidth(1.5f);
        leftAxis.addLimitLine(limitLine1);
        XAxis xAxis = chart.getXAxis();
        xAxis.setDrawGridLines(false);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setLabelCount(7, true);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                long minutes = (long) (value / 60000);
                return minutes + "";
            }
        });
    }

    private void showPaceChart() {
        TextView title = paceLayout.findViewById(R.id.title);
        title.setText("每公里配速");
        TextView name = paceLayout.findViewById(R.id.name);
        name.setText(getString(R.string.workout_chart_label_avg_pace));
        TextView name1 = paceLayout.findViewById(R.id.name1);
        name1.setText(getString(R.string.workout_chart_label_max_pace));
        TextView value = paceLayout.findViewById(R.id.value);
        TextView value1 = paceLayout.findViewById(R.id.value1);
        PaceHelper paceHelper = new PaceHelper();
        paceHelper.init(workout);
        if (workout.getSport() != Workout.TYPE_CYCLING || workout.getSport() != Workout.TYPE_RUNNING
                || workout.getSport() != Workout.TYPE_WALKING || !paceHelper.isPaceValid()) {
            paceView.setVisibility(View.GONE);
            return;
        }
        value.setText(paceHelper.getAvgPace());
        value1.setText(paceHelper.getMinPace());
        TextView unit = paceLayout.findViewById(R.id.unit);
        unit.setVisibility(View.GONE);
        paceList.setLayoutManager(new LinearLayoutManager(getContext()));
        if (paceHelper.getPacePointList() != null) {
            SportRecordPaceAdapter paceAdapter = new SportRecordPaceAdapter(paceHelper.getPacePointList());
            paceList.setAdapter(paceAdapter);
        }
    }

    private void showAltitudeChart() {
        ImageView image = altitudeLayout.findViewById(R.id.image);
        image.setImageResource(R.drawable.ic_sport_detail_altitude);
        TextView title = altitudeLayout.findViewById(R.id.title);
        title.setText(getString(R.string.workout_chart_axis_altitude));
        TextView name = altitudeLayout.findViewById(R.id.name);
        name.setText(getString(R.string.workout_chart_label_avg_altitude));
        TextView name1 = altitudeLayout.findViewById(R.id.name1);
        name1.setText(getString(R.string.workout_chart_label_max_altitude_pro));
        TextView unit = altitudeLayout.findViewById(R.id.unit);
        unit.setText(getString(R.string.workout_chart_axis_altitude));
        unit.setTextColor(getContext().getColor(R.color.color_11aefa));
        TextView value = altitudeLayout.findViewById(R.id.value);
        TextView value1 = altitudeLayout.findViewById(R.id.value1);
        WorkoutExtraInfo workoutExtraInfo = workout.getWorkoutExtraInfo();
        avgAltitude = (float) workoutExtraInfo.getAvgAltitude();
        value.setText(decimalFormat2.format(avgAltitude) + getString(R.string.unit_m));
        maxAltitude = (float) workoutExtraInfo.getMaxAltitude();
        value1.setText(decimalFormat2.format(maxAltitude) + getString(R.string.unit_m));
        List<ITrackPoint> trackpointList = workout.getTrackPointsForChart();
        if (trackpointList == null) {
            return;
        }
        altitudeEntries = new ArrayList<>();
        for (int i = 0; i < trackpointList.size(); i++) {
            altitudeEntries.add(new Entry(trackpointList.get(i).getTime() - trackpointList.get(0).getTime(),
                    (float) trackpointList.get(i).getAltitude()));
        }
        initLineChart(altitudeChart, altitudeEntries, maxAltitude, avgAltitude, getContext().getColor(R.color.color_11aefa),
                true, getContext().getColor(R.color.color_11aefa));
        if (workout.getSport() != Workout.TYPE_RUNNING && workout.getSport() != Workout.TYPE_TRAINING
                && (workout.getUpDistance() > Utils.DOUBLE_EPSILON || workout.getFlatDistance() > Utils.DOUBLE_EPSILON
                || workout.getDownDistance() > Utils.DOUBLE_EPSILON)) {
            double upDistance = workout.getUpDistance() + workout.getFlatDistance() + workout.getDownDistance();
            ArrayList<LinearPercentView.PercentItem> arrayList = new ArrayList<>();
            arrayList.add(new LinearPercentView.PercentItem(R.color.green_81d955,
                    "下坡：" + CommonUtil.getFormatDistance(workout.getDownDistance()) + UnitConstants.UNIT_SIZE_KM,
                    (workout.getDownDistance() / upDistance) * 100.0d));
            arrayList.add(new LinearPercentView.PercentItem(R.color.color_ffc107,
                    "平路：" + CommonUtil.getFormatDistance(workout.getFlatDistance()) + UnitConstants.UNIT_SIZE_KM,
                    (workout.getFlatDistance() / upDistance) * 100.0d));
            arrayList.add(new LinearPercentView.PercentItem(R.color.red_fb6c50,
                    "上坡：" + CommonUtil.getFormatDistance(workout.getUpDistance()) + UnitConstants.UNIT_SIZE_KM,
                    (workout.getUpDistance() / upDistance) * 100.0d));
            slopeView.setPercentItems(arrayList);
        }
    }

    private void showHeartRateChart() {
        if (workout.getMaxHeartrate() == 0) {
            heartRateView.setVisibility(View.GONE);
            return;
        }
        ImageView image = heartRateLayout.findViewById(R.id.image);
        image.setImageResource(R.drawable.ic_sport_detail_heart_rate);
        TextView title = heartRateLayout.findViewById(R.id.title);
        title.setText(getString(R.string.workout_chart_axis_heartrate));
        TextView name = heartRateLayout.findViewById(R.id.name);
        name.setText(getString(R.string.workout_chart_label_avg_heartrate_pro));
        TextView name1 = heartRateLayout.findViewById(R.id.name1);
        name1.setText(getString(R.string.workout_chart_label_max_heartrate_pro));
        TextView unit = heartRateLayout.findViewById(R.id.unit);
        unit.setText(getString(R.string.workout_chart_axis_heartrate));
        unit.setTextColor(getContext().getColor(R.color.color_fe4545));
        TextView value = heartRateLayout.findViewById(R.id.value);
        TextView value1 = heartRateLayout.findViewById(R.id.value1);
        avgHeartrate = workout.getAvgHeartrate();
        value.setText(avgHeartrate + getString(R.string.unit_bpm));
        maxHeartrate = workout.getMaxHeartrate();
        value1.setText(maxHeartrate + getString(R.string.unit_bpm));
        List<ITrackPoint> trackpointList = workout.getTrackPointsForChart();
        if (trackpointList == null) {
            return;
        }
        heartrateEntries = new ArrayList<>();
        for (int i = 0; i < trackpointList.size(); i++) {
            heartrateEntries.add(new Entry(trackpointList.get(i).getTime() - trackpointList.get(0).getTime(),
                    trackpointList.get(i).getHeartrate()));
        }
        initLineChart(heartRateChart, heartrateEntries, maxHeartrate, avgHeartrate, getContext().getColor(R.color.color_fe4545),
                false, 0);
        HeartrateSection heartrateSection = new HeartrateSection();
        heartrateSection.init(workout);
        int[] percents = heartrateSection.getPercents();
        heartRateList.setLayoutManager(new LinearLayoutManager(getContext()));
        if (percents != null) {
            SportRecordCadenceAdapter heartRateAdapter = new SportRecordCadenceAdapter(heartRateStrings,
                    heartRateBgs, percents, workout.getDuration());
            heartRateList.setAdapter(heartRateAdapter);
        }
    }

    private void showCadenceChart() {
        if (workout.getMaxCadence() == 0) {
            cadenceView.setVisibility(View.GONE);
            return;
        }
        ImageView image = cadenceLayout.findViewById(R.id.image);
        image.setImageResource(R.drawable.ic_sport_detail_cadence);
        TextView title = cadenceLayout.findViewById(R.id.title);
        title.setText(getString(R.string.workout_chart_axis_cadence));
        TextView name = cadenceLayout.findViewById(R.id.name);
        name.setText(getString(R.string.workout_chart_label_avg_cadence_pro));
        TextView name1 = cadenceLayout.findViewById(R.id.name1);
        name1.setText(getString(R.string.workout_chart_label_max_cadence_pro));
        TextView unit = cadenceLayout.findViewById(R.id.unit);
        unit.setText(getString(R.string.workout_chart_axis_cadence));
        TextView value = cadenceLayout.findViewById(R.id.value);
        TextView value1 = cadenceLayout.findViewById(R.id.value1);
        avgCadence = workout.getAvgCadence();
        value.setText(avgCadence + getString(R.string.unit_rpm));
        maxCadence = workout.getMaxCadence();
        value1.setText(maxCadence + getString(R.string.unit_rpm));
        List<ITrackPoint> trackpointList = workout.getTrackPointsForChart();
        if (trackpointList == null) {
            return;
        }
        cadenceEntries = new ArrayList<>();
        for (int i = 0; i < trackpointList.size(); i++) {
            cadenceEntries.add(new Entry(trackpointList.get(i).getTime() - trackpointList.get(0).getTime(),
                    trackpointList.get(i).getCadence()));
        }
        initLineChart(cadenceChart, cadenceEntries, maxCadence, avgCadence, getContext().getColor(R.color.color_21d352),
                false, 0);
        CadenceSection cadenceSection = new CadenceSection();
        cadenceSection.init(workout);
        int[] percents = cadenceSection.getPercents();
        cadenceList.setLayoutManager(new LinearLayoutManager(getContext()));
        if (percents != null) {
            SportRecordCadenceAdapter cadenceAdapter = new SportRecordCadenceAdapter(cadenceStrings,
                    cadenceBgs, percents, workout.getDuration());
            cadenceList.setAdapter(cadenceAdapter);
        }
    }

    private void showPowerChart() {
        WorkoutExtraInfo workoutExtraInfo = workout.getWorkoutExtraInfo();
        if (workoutExtraInfo.getMaxPower() <= Utils.DOUBLE_EPSILON) {
            powerView.setVisibility(View.GONE);
            return;
        }
        ImageView image = powerLayout.findViewById(R.id.image);
        image.setImageResource(R.drawable.ic_sport_detail_power);
        TextView title = powerLayout.findViewById(R.id.title);
        title.setText(getString(R.string.workout_chart_axis_power));
        TextView name = powerLayout.findViewById(R.id.name);
        name.setText(getString(R.string.workout_chart_label_avg_power_pro));
        TextView name1 = powerLayout.findViewById(R.id.name1);
        name1.setText(getString(R.string.workout_chart_label_max_power_pro));
        TextView unit = powerLayout.findViewById(R.id.unit);
        unit.setText(getString(R.string.workout_chart_axis_power));
        unit.setTextColor(getContext().getColor(R.color.color_fd6e22));
        TextView value = powerLayout.findViewById(R.id.value);
        TextView value1 = powerLayout.findViewById(R.id.value1);
        avgPower = (int) workoutExtraInfo.getAvgPower();
        value.setText(avgPower + getString(R.string.unit_power));
        maxPower = (int) workoutExtraInfo.getMaxPower();
        value1.setText(maxPower + getString(R.string.unit_power));
        List<ITrackPoint> trackpointList = workout.getTrackPointsForChart();
        if (trackpointList == null) {
            return;
        }
        powerEntries = new ArrayList<>();
        for (int i = 0; i < trackpointList.size(); i++) {
            powerEntries.add(new Entry(trackpointList.get(i).getTime() - trackpointList.get(0).getTime(),
                    (float) trackpointList.get(i).getPower()));
        }
        initLineChart(powerChart, powerEntries, maxPower, avgPower, getContext().getColor(R.color.color_fd6e22),
                false, 0);
        PowerSection powerSection = new PowerSection();
        powerSection.init(workout);
        int[] percents = powerSection.getPercents();
        powerList.setLayoutManager(new LinearLayoutManager(getContext()));
        if (percents != null) {
            SportRecordCadenceAdapter cadenceAdapter = new SportRecordCadenceAdapter(powerStrings,
                    powerBgs, percents, workout.getDuration());
            powerList.setAdapter(cadenceAdapter);
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(getActivity(), SportRecordChartActivity.class);
        if (v.getId() == R.id.speedLayout || v.getId() == R.id.speedChart) {
            intent.putExtra("type", 0);
        } else if (v.getId() == R.id.altitudeLayout || v.getId() == R.id.altitudeChart) {
            intent.putExtra("type", 1);
        } else if (v.getId() == R.id.heartRateLayout || v.getId() == R.id.heartRateChart) {
            intent.putExtra("type", 2);
        } else if (v.getId() == R.id.cadenceLayout || v.getId() == R.id.cadenceChart) {
            intent.putExtra("type", 3);
        } else if (v.getId() == R.id.powerLayout || v.getId() == R.id.powerChart) {
            intent.putExtra("type", 4);
        }
        intent.putExtra("workout", (Parcelable) workout);
        startActivity(intent);
    }
}